package com.foreverwin.jzymes.app.service.impl;

import com.foreverwin.jzymes.app.service.ILoginAdviceService;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.security.internal.*;
import com.sap.me.user.FindUserSiteConfigurationsByUserIdRequest;
import com.sap.me.user.UserConfigurationServiceInterface;
import com.sap.me.user.UserSiteConfiguration;
import com.visiprise.frame.service.ServiceLocator;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class LoginAdviceServiceImpl implements ILoginAdviceService {

    public boolean authenticateUser( String userId, String password ) throws BusinessException {
        UserAuthenticationServiceInterface authenticationService = ServiceLocator.getService("UserAuthenticationService");
        UserAuthorizationServiceInterface authorizationService = ServiceLocator.getService("UserAuthorizationService");
        authenticationService.authenticate(userId, password);
        authorizationService.validateRoleForUser(new ValidateRoleForUserRequest(userId, Role.SAP_ME_USER));
        return true;
    }

    public String findSiteByUserId( String userId ) throws BusinessException {
        UserManagementServiceInterface umService = ServiceLocator.getService( "com.sap.me.security", "UserManagementService" );
        UserConfigurationServiceInterface userService = ServiceLocator.getService( "com.sap.me.user", "UserConfigurationService" );

        FindUserByUserIdRequest findRequest = new FindUserByUserIdRequest();
        findRequest.setUserId(userId);
        UserManagementConfiguration userConfiguration = umService.findUserByUserId(findRequest);
        String site = userConfiguration.getDefaultSite();
        if( site == null ){
            FindUserSiteConfigurationsByUserIdRequest findSitesRequest = new FindUserSiteConfigurationsByUserIdRequest();
            findSitesRequest.setUserId(userConfiguration.getUserId());
            Collection sites = userService.findUserSiteConfigurationsByUserId(findSitesRequest);
            if (sites.size() > 0)
                site = ((UserSiteConfiguration)sites.iterator().next()).getSite();
        }
        return site;
    }

}
